package com.alipay.demo.config;


import com.alipay.api.AlipayRequest;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.demo.entity.OrderClazz;
import com.alipay.demo.util.JackJsonUtils;
import lombok.Getter;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: zhuzhiping
 * @description: 支付宝支付
 * @date: 2021/1/7 10:06
 */

@Getter
public enum AlipayTradeRequestEnum {
    /**
     * PC
     */
    PC(AlipayConfig.productCodeForPc, new AlipayTradePagePayRequest()),

    /**
     * APP
     */
    APP(AlipayConfig.productCodeForApp, new AlipayTradeWapPayRequest()),
    ;

    /**
     * 产品代码
     */
    private final String productCode;

    /**
     * 请求
     */
    private final AlipayRequest alipayRequest;

    AlipayTradeRequestEnum(String productCode, AlipayRequest alipayRequest) {
        this.productCode = productCode;
        this.alipayRequest = alipayRequest;
    }

    public static AlipayRequest getRequest(OrderClazz order) {
        AlipayTradeRequestEnum[] values = AlipayTradeRequestEnum.values();
        Map<String, AlipayRequest> alipayRequestMap = Arrays.stream(values).collect(Collectors.toMap(AlipayTradeRequestEnum::getProductCode, AlipayTradeRequestEnum::getAlipayRequest));
        String productCode = order.getProduct_code();

        if (productCode == null || "".equals(productCode = productCode.trim()) || (!alipayRequestMap.containsKey(productCode))) {
            throw new RuntimeException("错误的支付请求");
        }
        AlipayRequest alipayRequest = alipayRequestMap.get(productCode);

        alipayRequest.setReturnUrl(AlipayConfig.returnUrl);
        alipayRequest.setNotifyUrl(AlipayConfig.notifyUrl);
        //请求参数
        if (alipayRequest instanceof AlipayTradeWapPayRequest) {
            AlipayTradeWapPayRequest alipayTradeWapPayRequest = (AlipayTradeWapPayRequest) alipayRequest;
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(order.getOut_trade_no());
            model.setSubject(order.getSubject());
            model.setTotalAmount(order.getTotal_amount());
            model.setBody(order.getBody());
            model.setTimeoutExpress("2m");
            model.setProductCode(productCode);
            alipayTradeWapPayRequest.setBizModel(model);
            return alipayTradeWapPayRequest;
        } else {
            AlipayTradePagePayRequest alipayTradePagePayRequest = (AlipayTradePagePayRequest) alipayRequest;
            alipayTradePagePayRequest.setBizContent(JackJsonUtils.getJSONStr(order));
            return alipayTradePagePayRequest;
        }
    }

}
